const WebSocket = require('ws');
const http = require('http');

// 测试配置
const CONFIG = {
    server: {
        host: 'localhost',
        port: 3000,
        protocol: 'http'
    },
    testUser: {
        mobile: '17091271111',
        password: '123456',
        passwordHash: 'e10adc3949ba59abbe56e057f20f883e'
    }
};

class GemSocketTester {
    constructor() {
        this.ws = null;
        this.token = null;
        this.userId = null;
        this.characterId = null;
        this.characters = [];
        this.selectedCharacter = null;
        this.gems = [];
        this.testResults = [];
        this.currentTestIndex = 0;
    }

    async makeHttpRequest(path, method = 'GET', data = null) {
        return new Promise((resolve, reject) => {
            const options = {
                hostname: CONFIG.server.host,
                port: CONFIG.server.port,
                path: path,
                method: method,
                headers: {
                    'Content-Type': 'application/json',
                }
            };

            if (data) {
                const jsonData = JSON.stringify(data);
                options.headers['Content-Length'] = Buffer.byteLength(jsonData);
            }

            const req = http.request(options, (res) => {
                let responseData = '';
                res.on('data', (chunk) => {
                    responseData += chunk;
                });
                res.on('end', () => {
                    try {
                        const parsedData = JSON.parse(responseData);
                        resolve(parsedData);
                    } catch (error) {
                        reject(new Error(`响应解析失败: ${error.message}`));
                    }
                });
            });

            req.on('error', (error) => {
                reject(error);
            });

            if (data) {
                req.write(JSON.stringify(data));
            }
            req.end();
        });
    }

    async registerUser() {
        try {
            const res = await this.makeHttpRequest('/user-service/user/register', 'POST', {
                mobile: CONFIG.testUser.mobile,
                pwd: CONFIG.testUser.passwordHash,
                captcha: '123456'
            });
            console.log('📝 用户注册成功', res);
        } catch (error) {
            if (error.message.includes('MOBILE_EXISTS') || error.message.includes('已存在')) {
                console.log('👤 用户已存在，跳过注册');
            } else {
                console.log('⚠️ 注册失败:', error.message);
            }
        }
    }

    async login() {
        try {
            console.log('🔐 开始登录...');
            await this.registerUser();

            const loginData = await this.makeHttpRequest('/user-service/user/login', 'POST', {
                mobile: CONFIG.testUser.mobile,
                pwd: CONFIG.testUser.passwordHash
            });

            if (loginData.code === 0 && loginData.data) {
                this.userId = loginData.data.userId;
                this.token = loginData.data.accessToken;
                console.log(`✅ 登录成功: userId=${this.userId}`);
                return true;
            } else {
                console.error('❌ 登录失败:', loginData.msg || '未知错误');
                return false;
            }
        } catch (error) {
            console.error('❌ 登录失败:', error.message);
            return false;
        }
    }

    connectWebSocket() {
        return new Promise((resolve, reject) => {
            console.log('🔌 连接WebSocket...');
            const wsUrl = `ws://${CONFIG.server.host}:${CONFIG.server.port}/user-service/websocket?t=${this.token}`;
            this.ws = new WebSocket(wsUrl);

            this.ws.on('open', async () => {
                console.log('✅ WebSocket连接成功');
                this.setupMessageHandler();
                await this.delay(500);
                resolve();
            });

            this.ws.on('error', (error) => {
                console.log('❌ WebSocket连接失败:', error.message);
                reject(error);
            });

            this.ws.on('close', () => {
                console.log('🔌 WebSocket连接已关闭');
            });

            setTimeout(() => {
                if (this.ws.readyState === WebSocket.CONNECTING) {
                    this.ws.close();
                    reject(new Error('连接超时'));
                }
            }, 10000);
        });
    }

    setupMessageHandler() {
        this.ws.on('message', (data) => {
            try {
                const message = JSON.parse(data.toString());
                console.log('📨 收到消息:', JSON.stringify(message, null, 2));
                this.handleMessage(message);
            } catch (error) {
                console.error('❌ 消息解析失败:', error.message);
            }
        });
    }

    delay(ms) {
        return new Promise(resolve => setTimeout(resolve, ms));
    }

    handleMessage(message) {
        const { act_id, code, roleList, roleCount, data, msg } = message;

        switch (act_id) {
            case 3: // 角色列表查询
                if (roleList && Array.isArray(roleList)) {
                    this.characters = roleList;
                    console.log(`📋 获取到${roleCount || roleList.length}个角色`);
                    this.selectCharacter();
                }
                break;

            case 4: // 角色选择
                if (code === 0) {
                    console.log('🎯 角色选择成功');
                    this.characterId = this.selectedCharacter?.id;
                    this.queryGemInventory();
                } else {
                    console.error('❌ 角色选择失败:', msg);
                }
                break;

            case 6034: // 宝石背包查询
                if (code === 0) {
                    this.gems = message.list || [];
                    console.log(`✅ 获取到 ${this.gems.length} 个宝石`);
                    this.testSocketableEquipment();
                } else {
                    console.error('❌ 查询宝石背包失败:', msg);
                }
                break;

            case 1090: // 可镶嵌装备查询
                if (code === 0) {
                    const equipment = data || [];
                    console.log(`✅ 宝石可镶嵌装备数量: ${equipment.length}`);
                    // 从当前测试的宝石获取ID
                    const currentGem = this.gems[this.currentTestIndex - 1];
                    this.recordTestResult(currentGem ? currentGem.id : null, equipment);
                } else {
                    console.error('❌ 查询可镶嵌装备失败:', msg);
                    const currentGem = this.gems[this.currentTestIndex - 1];
                    this.recordTestResult(currentGem ? currentGem.id : null, [], msg);
                }
                break;
        }
    }

    sendMessage(c, d = null) {
        if (this.ws && this.ws.readyState === WebSocket.OPEN) {
            const message = { c, d };
            this.ws.send(JSON.stringify(message));
            console.log(`📤 发送消息: ${JSON.stringify(message)}`);
        } else {
            console.error('❌ WebSocket未连接');
        }
    }

    queryCharacters() {
        console.log('👤 查询角色列表...');
        this.sendMessage(3);
    }

    selectCharacter() {
        if (this.characters.length === 0) {
            console.log('⚠️ 没有可选择的角色');
            return;
        }

        const targetCharacter = this.characters[0];
        this.selectedCharacter = targetCharacter;
        console.log(`🎯 选择角色: ${targetCharacter.name} (ID: ${targetCharacter.id})`);
        this.sendMessage(4, { characterId: targetCharacter.id });
    }

    queryGemInventory() {
        console.log('💎 查询宝石背包...');
        this.sendMessage(6034, { pageNum: 0 });
    }

    testSocketableEquipment() {
        console.log('\n🧪 开始测试宝石镶嵌逻辑...');

        if (this.gems.length === 0) {
            console.log('⚠️ 没有宝石可测试');
            return;
        }

        this.currentTestIndex = 0;
        const testNextGem = () => {
            if (this.currentTestIndex >= this.gems.length) {
                this.showTestResults();
                return;
            }

            const gem = this.gems[this.currentTestIndex];
            console.log(`\n💎 测试宝石 ${this.currentTestIndex + 1}/${this.gems.length}: ${gem.name} (ID: ${gem.id})`);

            // 发送1090命令查询可镶嵌装备
            this.sendMessage(1090, {
                id: gem.id
            });

            this.currentTestIndex++;

            // 等待2秒后测试下一个宝石
            setTimeout(testNextGem, 2000);
        };

        testNextGem();
    }

    recordTestResult(gemId, equipment, error = null) {
        const gem = this.gems.find(g => g.id === gemId);
        const result = {
            gemId: gemId || '未知',
            gemName: gem ? gem.name : '未知宝石',
            gemType: gem ? gem.type : '未知类型',
            equipmentCount: equipment.length,
            equipment: equipment,
            error: error,
            timestamp: new Date().toISOString()
        };

        this.testResults.push(result);

        if (error) {
            console.log(`❌ 宝石 ${result.gemName} 测试失败: ${error}`);
        } else {
            console.log(`✅ 宝石 ${result.gemName} 可镶嵌 ${equipment.length} 个装备`);
            if (equipment.length > 0) {
                equipment.forEach(eq => {
                    console.log(`   - ${eq.name} (ID: ${eq.id})`);
                });
            }
        }
    }

    showTestResults() {
        console.log('\n📊 测试结果汇总:');
        console.log('='.repeat(80));

        const totalGems = this.testResults.length;
        const successCount = this.testResults.filter(r => !r.error).length;
        const errorCount = this.testResults.filter(r => r.error).length;

        console.log(`总测试宝石数: ${totalGems}`);
        console.log(`成功测试数: ${successCount}`);
        console.log(`失败测试数: ${errorCount}`);
        console.log(`成功率: ${((successCount / totalGems) * 100).toFixed(2)}%`);

        console.log('\n📋 详细测试结果:');
        this.testResults.forEach((result, index) => {
            console.log(`\n${index + 1}. 宝石: ${result.gemName} (ID: ${result.gemId})`);
            console.log(`   类型: ${result.gemType}`);
            console.log(`   可镶嵌装备数: ${result.equipmentCount}`);

            if (result.error) {
                console.log(`   ❌ 错误: ${result.error}`);
            } else if (result.equipmentCount > 0) {
                console.log(`   ✅ 可镶嵌装备:`);
                result.equipment.forEach(eq => {
                    console.log(`     - ${eq.name} (ID: ${eq.id})`);
                });
            } else {
                console.log(`   ⚠️ 无可镶嵌装备`);
            }
        });

        // 分析特殊属性宝石
        this.analyzeSpecialAttributes();

        console.log('\n✅ 测试完成！');
        this.ws.close();
    }

    analyzeSpecialAttributes() {
        console.log('\n🔍 特殊属性分析:');

        const specialGems = this.testResults.filter(result => {
            const gem = this.gems.find(g => g.id === result.gemId);
            return gem && (gem.name.includes('黑曜石') || gem.name.includes('乾坤珠'));
        });

        if (specialGems.length > 0) {
            console.log(`发现 ${specialGems.length} 个特殊属性宝石:`);
            specialGems.forEach(result => {
                console.log(`\n💎 ${result.gemName}:`);
                console.log(`  可镶嵌装备数: ${result.equipmentCount}`);

                if (result.equipmentCount > 0) {
                    const equipmentTypes = result.equipment.map(eq => eq.type);
                    console.log(`  装备类型: [${equipmentTypes.join(', ')}]`);

                    // 检查是否只支持武器(2)和护腕(5)
                    const expectedTypes = [2, 5];
                    const hasUnexpectedTypes = equipmentTypes.some(type => !expectedTypes.includes(type));

                    if (hasUnexpectedTypes) {
                        console.log(`  ⚠️ 警告: 包含非预期的装备类型`);
                    } else {
                        console.log(`  ✅ 装备类型符合预期 (武器和护腕)`);
                    }
                }
            });
        }
    }

    async run() {
        try {
            console.log('🧪 开始宝石镶嵌逻辑测试...\n');

            const loginSuccess = await this.login();
            if (!loginSuccess) {
                return;
            }

            await this.connectWebSocket();

            // 等待连接稳定后查询角色
            setTimeout(() => {
                this.queryCharacters();
            }, 1000);

        } catch (error) {
            console.error('❌ 测试失败:', error);
        }
    }
}

// 运行测试
const tester = new GemSocketTester();
tester.run().catch(console.error);
